package com.ktjiaoyu.controller;

import com.ktjiaoyu.entity.SysRole;
import com.ktjiaoyu.entity.SysUser;
import com.ktjiaoyu.service.SysRoleService;
import com.ktjiaoyu.service.SysUserService;
import com.ktjiaoyu.service.UploadService;
import com.ktjiaoyu.utils.Constants;
import com.ktjiaoyu.utils.Page;
import jakarta.annotation.Resource;
import jakarta.servlet.jsp.jstl.sql.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/main/user")
public class UserController extends BaseController{
    private static final Logger looger= LoggerFactory.getLogger(UserController.class);
    @Resource
    private SysUserService sysUserService;
    @Resource
    private SysRoleService sysRoleService;
    @Resource
    @Qualifier("toLocalUploadServiceImpl")
    private UploadService uploadService;

    @GetMapping("/page")
    public String page(Model model, SysUser condoition,
                       @RequestParam(value = "pageNo", defaultValue = "1")Integer pageNo,
                       @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize) {
        Page<SysUser> page=null;
        try{
            //查询用户的分页信息
            page=sysUserService.findPage(condoition,pageNo,pageSize);
            //查询所有角色
            List<SysRole> rolesList=sysRoleService.findAll();
            //将分页数据,角色列表和查询条件设置到模型数据中
            model.addAttribute("pageInfo",page);
            model.addAttribute("rolesList",rolesList);
            model.addAttribute("condoition",condoition);
        } catch (Exception e) {
            looger.error("执行UserController.page(Model,SysUser,Integer,Integer)方法出现异常.", e);
            throw new RuntimeException(e);
        }
        return "user/page";
    }
    /**
     * 跳转到保存用户页面
     */
    @GetMapping("/save")
    public String save(Model model) {
        List<SysRole> roleList=null;
        try{
            roleList=sysRoleService.findAll();
            //有角色下拉框需要数据
            model.addAttribute("roleList",roleList);
            //回显数据时需要 sysUser,这里给个空对象避免出错
            model.addAttribute("sysUser",new SysUser());
        }catch (Exception e){
            looger.error("执行UserController.save(Model)方法出现异常.", e);
            throw new RuntimeException(e);
        }
        return "user/save";
    }

    /**
     * 保存或修改数据接口
     */
    @PostMapping("/save")
    public String deSave(SysUser sysUser, @RequestParam("idPic") MultipartFile idPic,
                         @RequestParam("workPic") MultipartFile workPic){
        //允许的上传图片后缀
        String []allowImageExt={"jpg","png","jpeg","gif","bmp"};
        try{
            //上传
            if (idPic!=null){
                //调用上传文件服务,返回上传成功后的路径 为null 表示没上传
                String idPicPath=uploadService.uploadFile(idPic,allowImageExt);
                sysUser.setIdPicPath(idPicPath);
            }
            //通过父类的session方法获取登录用户,由于泛型自动转换无需强转
            SysUser loginUser=session(Constants.SESSION_USER);
            if (sysUser.getId()==null){
                //如果是修改用户,关联创建用户为当前登录用户
                sysUser.setCreatedUserId(loginUser.getId());
                sysUser.setCreatedTime(new Date());
            }else {
                //如果是修改用户,关联修改用户为当前登录用户
                sysUser.setUpdatedUserId(loginUser.getId());
                sysUser.setUpdatedTime(new Date());
            }
            //新增和修改公用同一个业务方法
            boolean ok =sysUserService.saveOrUpdate(sysUser);
            if ( ok){
                //保存成功 跳转到列表页面
                return redirect("/main/user/page");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return "user/save";
    }

    @GetMapping("/view/{id}")
    public String view(@PathVariable("id")Long id,Model  model){
        SysUser sysUser=null;
        try{
            sysUser=sysUserService.findById(id);
        } catch (Exception e) {
            looger.error("执行UserController.view(@PathVariable(\"id\")Long id,Model  model)方法出现异常.", e);
            throw new RuntimeException(e);
        }
        return "user/view";
    }

    @GetMapping("/edit")
    public String toEit(@RequestParam("id")Long id,Model model){
        SysUser sysUser=null;
        List<SysRole> roleList=null;
        try{
            sysUser=sysUserService.findById(id);
            roleList=sysRoleService.findAll();
            //有角色下拉框需要数据
            model.addAttribute("roleList",roleList);
            //会显示数据时需要 sysUser 这里给个空对象避免出错
            model.addAttribute("sysUser",sysUser);
        } catch (Exception e) {
            looger.error("执行UserController.toEit(@RequestParam(\"id\")Long id,Model model)方法出现异常.", e);
            throw new RuntimeException(e);
        }
        return "user/save";
    }
}